<script setup>
import { useAdvAllList, useAdvState, usePlaceState,usatTonued } from '@/hooks/sotet'
import { getContentApi, addAdvtApi, getAdvInfoApi, editAdvtApi, delAdvtApi } from '@/api/seek.js'
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus'
// ============================================
const total = ref(0)
const list = ref([])

const initData = async () => {
  const { data: { rows, count } } = await getContentApi(queryData)
  // console.log(res);
  // console.log(rows);
  // console.log(res.data.rows);
  // console.log(res.data.count); 
  list.value = rows
  total.value = count
}
const placedat = usatTonued()
const placeList = usePlaceState()
// console.log(usePlaceList);
const stateList = useAdvState()
// console.log(stateList);a
const advAllList = useAdvAllList()
// console.log(advAllList);
// ============================================
// 创建列表功能
const queryData = reactive({
  current: 1, //每页的页码
  pageSize: 3, //每页数量
  name: '',  //广告名称
  community_code: '',  //小区名称
  type: '', //广告位置
  status: null//广告状态
})

// ============================================
onMounted(() => {
  initData()
  // console.log(stateList)
  // console.log(placeList)
})

//=============================================
// 广告状态
const showState = (val) => {
  let res = stateList.find(item => item.value === val * 1)
  return res ? res.label : '未知'
}
// 广告位置
const showData = (val) => {
  let res = placeList.find(item => item.value === val * 1)
  return res ? res.label : '未知'
}

// ===========================================
// 每页数量切换
const sizeChange = (val) => {
  queryData.pageSize = val
  initData()
}
//页码切换
const currentChange = (val) => {
  queryData.current = val
  initData()
}
// 搜索
const onSearch = () => {
  queryData.current = 1
  initData()
}
// 重置
const onReset = () => {
  Object.assign(
    queryData, {
    current: 1, //每页的页码
    pageSize: 3, //每页数量
    name: '',  //广告名称
    community_code: '',  //小区名称
    type: '', //广告位置
    status: null//广告状态
  })
  initData()
}
// ============================================
// 弹框控制
const isShow = ref(false)
//关闭校验
const closeHandler = () => {
  // console.log(415);
  formRef.value.resetFields()
  // 重置表单
  Object.assign(formData, {
    community_code: "",
    link: "", //增加广告
    name: "",
    pic_url: "",
    remark: "",   //备注信息
    status: 1,
    type: '',
  })
}
//=============================================
// 表单校验
const formRef = ref()
// ============================================
// 新增区域绑定
const formData = reactive({
  community_code: "",
  link: "", //增加广告
  name: "",
  pic_url: "",
  remark: "",   //备注信息
  status: 1,
  type: '',
})
// 新增区域表单验证规则
const fromRules = {
  // community_code: [{ required: true, message: '请输入', trigger: 'change' }],
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  // pic_url: [{ required: true, message: '请输入', trigger: 'blur' }],
  type: [{ required: true, message: '请输入', trigger: 'change' }]
}
// 
// 提交按钮表单校验
const onsubmit = async () => {
  try {
    // 提交校验
    await formRef.value.validate()
    const data = toRaw(formData)
    formData.id ? await editAdvtApi(data) : await addAdvtApi(data)
    // 提交数据
    // await addAdvtApi(toRaw(formData))
    // 提示成功
    ElMessage.success('增加成功')
    // 关闭弹窗
    isShow.value = false
    // 列表刷新
    // console.log(1111);
    initData()

  } catch (error) {
    console.log(error);
  }
}
// ============================================
// 编辑功能
const editRow = (id) => {
  // isShow.value = true
  replyData(id)
}
// 编辑功能
const addRef = ref()
// 数据回显
const replyData = async (id) => {
  // alert(id)
  let { data } = await getAdvInfoApi(id)
  // console.log(res);
  Object.assign(formData, data)
  isShow.value = true
}
// 标题
const title = computed(() => {
  return formData.id ? '编辑广告' : '新增广告'
})

// 删除功能
const delRow = async (id) => {
  // alert(id)
  await delAdvtApi(id)
  ElMessage.success('删除成功')
  if (queryData.pageSize > 1 && list.value.length === 1) queryData.current--
  initData()
}
// 关闭抽屉
const closeDra = async () => {
  Object.assign(formData, {
    community_code: "",
    link: "", //增加广告
    name: "",
    pic_url: "",
    remark: "",   //备注信息
    status: 1,
    type: '',
  })
  await nextTick(() => {
    formRef.value.resetFields()
  })
}
</script>

<template>
  <div>
    <br>
    <div class="advertising">
      <span>
        <h3 style="font-weight: 700; display: inline-block;">广告管理</h3>
        用于管理广告图相关的内容信息
      </span>
      <!-- 搜索区域 -->
      <el-card>
        <el-form label-position="top" :inline="true" size="small">
          <el-form-item label="小区名称">
            <el-select placeholder="请输入" v-model="queryData.community_code" clearable>
              <el-option v-for="item in placedat" :key="item.id" :label="item.name" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="广告名称">
            <el-input placeholder="请输入" v-model="queryData.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="广告位置">
            <el-select placeholder="请输入" size="small" v-model="queryData.type" clearable>
              <el-option v-for="( item, index ) in  placeList " :key="index" :label="item.label" :value="item.label">
                {{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="广告状态">
            <el-select placeholder="请输入" size="small" v-model="queryData.status" clearable>
              <el-option v-for="( item, index ) in  stateList " :key="index" :label="item.label" :value="item.label">
                {{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div id="mTop">
              <el-button type="primary" @click="onSearch">搜索</el-button>
              <el-button @click="onReset">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      <br>
      <!-- =============================================================== -->
      <!-- 工具区域 -->
      <el-card>
        <el-row type="flex" justify="space-between">
          <div></div>
          <div>
            <el-button type="primary" size="mini" @click="isShow = true">新增广告</el-button>
            <!-- 抽屉区域 -->
            <el-drawer @close="closeDra" v-model="isShow" :title="title" size="600px" :before-close="handleClose">
              <!-- 新增区域 -->
              <el-form :model="formData" :rules="fromRules" ref="formRef" :inline="true" size="small"
                label-position="top">
                <el-form-item label="所属小区" prop="community_code">
                  <el-select placeholder="请输入" v-model="formData.community_code" clearable>
                    <el-option v-for="item in placedat" :key="item.id" :label="item.name" :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="广告名称" prop="name">
                  <el-input v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="链接内容">
                  <el-input v-model="formData.link"></el-input>
                </el-form-item>
                <el-form-item label="广告位置" prop="type">
                  <el-select placeholder="请输入" size="small" v-model.number="formData.type" clearable>
                    <el-option v-for="( item, index ) in  placeList " :key="index" :label="item.label"
                      :value="item.value">
                      {{ item.label }}
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备注信息">
                  <el-input v-model="formData.remark"></el-input>
                </el-form-item>
                <el-form-item label="启用状态">
                  <el-radio-group v-model="formData.status" class="ml-4">
                    <el-radio :label="1" size="small">禁用</el-radio>
                    <el-radio :label="2" size="small">启用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="上传图片">
                  <ImageUpload v-model="formData.pic_url" :type="'adv'" />
                </el-form-item>
                <el-form-item class="bottom">
                  <el-button @click="closeHandler">取消</el-button>
                  <el-button type="primary" @click="onsubmit">确定</el-button>
                </el-form-item>
              </el-form>
            </el-drawer>
          </div>
        </el-row>
        <br>
        <!-- 表格区域 -->
        <el-table :data="list" border stript>
          <el-table-column type="index" label="ID" width="40"></el-table-column>
          <el-table-column prop="name" label="广告名称" width="180"></el-table-column>
          <el-table-column label="图片内容">
            <template #default="{ row }">
              <!-- {{ row.pic_url}} -->
              <ImagePreview :src="row.pic_url" />
              <!-- <el-image style="width: 100px; height: 100px" :src="'http://124.223.14.236:8881' + row.pic_url" /> -->
            </template>
          </el-table-column>
          <el-table-column prop="link" label="链接地址"></el-table-column>
          <el-table-column label="广告位置">
            <template #default="{ row }">
              {{ showData(row.type) }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="{ row }">
              {{ showState(row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size='small' @click="editRow(row.id)" type="text">编辑</el-button>
              <el-popconfirm title="确定删除嘛?" @confirm="delRow(row.id)">
                <template #reference>

                  <el-button size='small' type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- =============================================================== -->
        <br>
        <!-- 分页区域 -->
        <el-pagination small="true" @size-change="sizeChange" @current-change="currentChange"
          v-model:current-change="queryData.current" :page-sizes="[3, 5, 10]" v-model:page-size="queryData.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" background>
        </el-pagination>
      </el-card>
      <br>
    </div>
  </div>
</template>
<style>
#mTop {
  margin-top: 23px;
}

.advertising {
  margin: 0 auto;
}

.bottom {
  margin-top: 100px;
  margin-left: -20px;
}
</style>